package foo.websystem.action;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import foo.base.BaseAction;
import foo.websystem.bo.SystemBO;
import foo.websystem.vo.LoginForm;
import foo.websystem.vo.SessionUser;

@Controller
public class LoginAction extends BaseAction {

	@Autowired
	private SystemBO systemBO;

	public LoginAction() {
		logger.debug("建立了LoginAction");
	}

	@RequestMapping(value = "/initLogin")
	public String initLogin(Model model, HttpSession session) {
		LoginForm loginForm = new LoginForm();
		session.removeAttribute(Consts.USER);
		model.addAttribute("loginForm", loginForm);
		model.addAttribute(Consts.MSG, "~~Welcome~~");
		return LOGIN;
	}

	@RequestMapping(value = "/logout")
	public String logout(Model model, HttpSession session) {
		SessionUser user = (SessionUser) session.getAttribute(Consts.USER);
		LoginForm loginForm = new LoginForm();
		model.addAttribute("msg",
				"Bye 了 , " + (user == null ? "親愛~" : user.getUserName()));
		model.addAttribute("loginForm", loginForm);
		session.removeAttribute(Consts.USER);
		return LOGIN;
	}

	static final String LOGIN = "loginPage";

	@RequestMapping(value = "/login")
	public ModelAndView login(@ModelAttribute LoginForm loginForm,
			HttpSession session) {
		String url = LOGIN;
		ModelAndView mav = new ModelAndView();
		try {
			systemBO.login(session, loginForm.getUserId(),
					loginForm.getPassword());
			url = "main";
			mav.addObject(Consts.MSG, "Welcome~ Baby...");
			mav.setViewName(url);
		} catch (Exception e) {
			mav.addObject(Consts.MSG, e.getLocalizedMessage());
			mav.setViewName(url);
		}
		return goToMain(mav);
	}

	@RequestMapping(value = "/main")
	public ModelAndView goToMain(ModelAndView model) {
		return model;
	}
}
